﻿//-----------------------------------------------------------------------
// <copyright file="ValueRangeTextBoxFieldDefinition.cs" company="Jamie Knight">
// Copyright (c) Jamie Knight. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using DevKnightlie.WPF.AutoForm.FieldDefinitions;
using Xceed.Wpf.Toolkit.Primitives;
using PropertyAttributes = System.Reflection.PropertyAttributes;

namespace DevKnightlie.WPF.AutoForm.WPFToolkit.FieldDefinitions
{
    /// <summary>
    /// Field definition which creates a ValueRangeTextBox control
    /// </summary>
    public class ValueRangeTextBoxFieldDefinition:BaseFieldDefinition
    {
        #region Properties

        /// <summary>
        /// Sets or returns a value indicating the minimum allowable value of the control
        /// </summary>
        public object MinValue { get; set; }

        /// <summary>
        /// Sets or returns a value indicating the maximum alowable value of the control
        /// </summary>
        public object MaxValue { get; set; }

        #endregion

        #region Methods

        public override void BuildInputControl()
        {
            ValueRangeTextBox textBox = new ValueRangeTextBox()
            {
                HorizontalContentAlignment = HorizontalAlignment.Left,
                VerticalContentAlignment = VerticalAlignment.Center,
                MinValue = MinValue,
                MaxValue = MaxValue
            };
            if (PropertyInfo != null)
            {
                var attrs = (RangeAttribute[])PropertyInfo.GetCustomAttributes(typeof(RangeAttribute), false);
                if (attrs.Length > 0)
                {
                    RangeAttribute attr = attrs[0];
                    textBox.MinValue = attr.Minimum;
                    textBox.MaxValue = attr.Maximum;
                }
            }
            Binding valueBinding = new Binding(PropertyName);
            BindingOperations.SetBinding(textBox, ValueRangeTextBox.ValueProperty, valueBinding);
            SetupEnabledBinding(textBox);
            InputControl = ContainerControl = textBox;
        }

        #endregion
    }
}
